package cn.facetoken.homer;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class PhotoRegistrationViewHolder
        extends RecyclerView.ViewHolder
        implements View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener, DialogInterface.OnClickListener {

    PhotoRegistrationViewHolder(@NonNull final Activity activity, @NonNull final PhotoRegistrationRecyclerViewAdapter adapter, @NonNull final View view) {
        super(view);
        this.activity = activity;
        this.adapter = adapter;

        nameView = view.findViewById(R.id.name);
        photoView = view.findViewById(R.id.photo);

        if (null == nameView) {
            Log.e(getClass().getSimpleName(), "idView is null.");
        }
        if (null == photoView) {
            Log.e(getClass().getSimpleName(), "contentView is null.");
        }

        view.setOnCreateContextMenuListener(this);
    }

    private @NonNull final Activity activity;
    private @NonNull final PhotoRegistrationRecyclerViewAdapter adapter;

    final TextView nameView;
    final ImageView photoView;

    private static final byte ITEM_ID_COPY_FACE_FEATURE = 1;
    private static final byte ITEM_ID_COPY_EYEPRINT_FEATURE = 2;

    private static final byte ITEM_ID_REMOVE = 91;

    @Override
    public void onCreateContextMenu(@NonNull final ContextMenu menu, @NonNull final View view, @NonNull final ContextMenu.ContextMenuInfo menuInfo) {
        menu.setHeaderTitle(loadStringResource(R.string.menu_header_title));

        addMenuItem(menu, ITEM_ID_COPY_FACE_FEATURE, R.string.copy_face_feature_menu_item);
        addMenuItem(menu, ITEM_ID_COPY_EYEPRINT_FEATURE, R.string.copy_eyeprint_feature_menu_item);
        addMenuItem(menu, ITEM_ID_REMOVE, R.string.remove_menu_item);
    }

    private void addMenuItem(@NonNull final ContextMenu menu, final byte itemId, final int resourceId) {
        @NonNull final MenuItem menuItem = menu.add(itemId / 10, itemId, itemId, loadStringResource(resourceId));
        menuItem.setOnMenuItemClickListener(this);
    }

    @NonNull
    private String loadStringResource(final int resourceId) {
        return itemView.getContext().getResources().getString(resourceId);
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case ITEM_ID_COPY_FACE_FEATURE:
                onCopyFaceFeatureMenuItemClicked();
                break;
            case ITEM_ID_COPY_EYEPRINT_FEATURE:
                onCopyEyeprintFeatureMenuItemClicked();
                break;
            case ITEM_ID_REMOVE:
                onRemoveMenuItemClicked();
                break;
            default:
        }
        return true;
    }

    private void onCopyFaceFeatureMenuItemClicked() {
        Log.d(getClass().getSimpleName(), "onCopyFaceFeatureMenuItemClicked()");
        copyFeature(R.string.face_feature, R.id.tag_key_face_feature);
    }

    private void onCopyEyeprintFeatureMenuItemClicked() {
        Log.d(getClass().getSimpleName(), "onCopyEyeprintFeatureMenuItemClicked()");
        copyFeature(R.string.eyeprint_feature, R.id.tag_key_eyeprint_feature);
    }

    private void copyFeature(final int resourceId, final int tag_key) {
        @NonNull final String label = String.format("%s %s", nameView.getText(), loadStringResource(resourceId));
        @NonNull final String text = String.format("%s: %s", loadStringResource(resourceId), itemView.getTag(tag_key));
        getClipboardManager().setPrimaryClip(ClipData.newPlainText(label, text));
    }

    @NonNull
    private ClipboardManager getClipboardManager() {
        return (ClipboardManager)
                itemView.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
    }

    private void onRemoveMenuItemClicked() {
        Log.d(getClass().getSimpleName(), "onRemoveMenuItemClicked()");

        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(itemView.getContext());
        dialogBuilder.setTitle(R.string.remove_face_registration_title).
                setMessage(R.string.remove_face_registration_message).
                setPositiveButton(android.R.string.ok, this).
                setNegativeButton(android.R.string.cancel, this).
                setCancelable(true).show();
    }

    @Override
    public void onClick(@NonNull final DialogInterface dialogInterface, final int which) {
        switch (which) {
            case DialogInterface.BUTTON_POSITIVE:
                Log.i(getClass().getSimpleName(), String.format("onClick(Dialog, button): User clicked the positive button. Removing item: id = %s.", itemView.getTag(R.id.tag_key_id)));
                removeSelectedItem();
                break;
            case DialogInterface.BUTTON_NEGATIVE:
            case DialogInterface.BUTTON_NEUTRAL:
            default:
                Log.d(getClass().getSimpleName(), "onClick(Dialog, button): User did not click the positive button.");
        }
    }

    private void removeSelectedItem() {
        Log.d(getClass().getSimpleName(), String.format("removeSelectedItem(): View.tag = %s.", itemView.getTag()));
        Log.d(getClass().getSimpleName(), String.format("removeSelectedItem(): View.tag(id) = %s.", itemView.getTag(R.id.tag_key_id)));

        final long id = null == itemView.getTag(R.id.tag_key_id) ? 0L : (Long) itemView.getTag(R.id.tag_key_id);
        Log.d(getClass().getSimpleName(), String.format("removeSelectedItem(): id = %d", id));
        if (0==id) {
            return;
        }

        @NonNull final FaceSample faceSample = new FaceSample();
        faceSample.id = id;
        new Thread(() -> {
            MainApplication.getMainDatabase().faceSampleDao().delete(faceSample);
            final int position = null==itemView.getTag() ? 0 : (Integer)itemView.getTag();
            adapter.photoRegistrationList.remove(position);
            activity.runOnUiThread(() -> adapter.notifyItemRemoved(position));
        }).start();
    }
}
